#!/usr/bin/env python
# -*- coding:UTF-8 -*-
from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django import forms
from django.contrib.auth import authenticate
import sys
import traceback
import logging
import cgi, cgitb
from os import environ
from string import strip, split
import datetime, time
import MySQLdb
import base64
import socket
from struct import *
import ctypes
import json
import hashlib
import os
from django.contrib.auth import login as djangologin
from django.conf import settings as original_settings
# from requests import auth

import web_XZDQ_V1_0.MySQLDB as MySQLDB
import web_XZDQ_V1_0.PowerID as PowerID
import web_XZDQ_V1_0.Common as Common
import web_XZDQ_V1_0.FileUtil as FileUtil
from django.views.decorators.csrf import csrf_exempt


# Create your views here.

# 功能：登录界面
# 输入参数：request
# 返回参数：response/login.html
def login(request):
    response = render(request, 'login.html', {})
    return response


# 功能：登录信息验证
# 输入参数：request
# 返回参数：jsonstr/data = {"status":flag,"message":message,"data":userdata}
def logininfo(request):
    # IDName = request.GET["UName"]
    # MD5 = request.GET["password"]
    IDName = request.POST["UName"]
    MD5 = request.POST["password"]
    pw = request.POST.get("pw","")
    row = MySQLDB.SelectMySql(
        "SELECT role_id,user_id,dept_id FROM t_sys_user WHERE login_name = '%s' AND password = '%s' AND status = 1;" % (
        IDName, MD5))
    userdata = []
    flag = "fail"
    message = u"登录失败"
    try:
        if len(row) > 0:
            if row[0][2] == 202:
                userdata.append("技术员")
                userdata.append(int(row[0][0]))
            elif row[0][2] == 203:
                userdata.append("巡检员")
                userdata.append(int(row[0][0]))
            elif row[0][2] == 201:
                userdata.append("维护员")
                userdata.append(int(row[0][0]))
            else:
                userdata.append("员工")
                userdata.append(int(row[0][0]))
            flag = "success"
            message = u"登录成功"
            # 用户登录 兼容性
            # user = auth.authenticate(username=IDName, password=pw)
            # if user is not None and user.is_active:
            #     Correct password, and the user is marked "active"
                # auth.login(request, user)

            user = authenticate(username=IDName, password=pw)
            # print 'IDName',IDName
            # print 'pw',pw
            if user is not None:
                if user.is_active:
                    djangologin(request, user)
                    # Correct password, and the user is marked "active"
        else:
            userdata.append("null")
            userdata.append(0)
    except:
        userdata.append("error")
        userdata.append(0)
    userdata.append(IDName)  # userdata数组结构 [0]登录人员权限名称 [1]权限代码 [2]用户名 [3]用户ID [4]登录MD5
    userdata.append(row[0][1])
    # 生成loginflag变量 t_sys_user表description字段存储 cookie与数据库中进行对比若不一致则不具备访问权限 跳转至登录界面即url='/'
    locatime = time.strftime("%Y-%m-%d %X", time.localtime())
    MD5Str = locatime + str(IDName)
    tmpmd5 = hashlib.md5()
    tmpmd5.update(MD5Str)
    loginflag = tmpmd5.hexdigest()
    userdata.append(loginflag)
    row = MySQLDB.CommitMySql("update t_sys_user set valid_md5 = '%s' where login_name = '%s'" % (loginflag, IDName))
    data = {
        "status": flag,
        "message": message,
        "data": userdata
    }
    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


# 功能：首页界面
# 输入参数：request
# 返回参数：response/login.html
def home(request):
    # 取得系统设置cookie超时时间，若未设置，则默认7200秒
    timeoutCount = getattr(original_settings, "TIMEOUTCOUNT", 7200)
    loginmd5 = request.GET['loginmd5']
    userid = request.GET['userid']
    # menustr = PowerID.roleid(userid)
    response = render(request, 'home.html', {})
    response.set_cookie('userid', userid, timeoutCount)
    response.set_cookie('loginmd5', loginmd5, timeoutCount)
    return response


def test(request):
    recordCode = Common.GenDocNum("t_check_record", "1")  # 定检生成编号
    return render(request, "test.html", {})


@csrf_exempt
def uploadFile(request):
    if request.method == "POST":
        myFile = request.FILES.getlist("myfile")
        # 上传文件
        d = FileUtil.UploadFiles(myFile)
        # 保存数据
        if d["status"] == 1:

            for f in d:
                str1 = f["f_name"]
                str2 = f["f_url"]
                str3 = 1
    return HttpResponse(d)


def big_file_download(request):
    # 读取数据
    data = Common.GetParamInfoByCode("bridgeType")
    # 生成csv文件
    header = ["id", "name"]
    filePath = FileUtil.WriteCSV(data, header)
    return DownloadFile(filePath, "桥梁数据.csv")


# 功能：下载文件
# 输入参数：filePath：文件路径；fileName:文件名称
# 输出参数：response
def DownloadFile(filePath, fileName):
    def file_iterator(file_name, chunk_size=512):
        with open(file_name) as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    response = StreamingHttpResponse(file_iterator(filePath))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(fileName)
    return response


# 功能：文件上传
# 输入参数：request
# 返回参数：response
def UploadFile():
    fileName = ""
    myFile = request.FILES.getlist("myfile", None)
    if not myFile:
        data = {
            "status": 0,
            "message": u"no file",
            "data": []
        }
    try:
        for f in myFile:
            fileName = FileUtil.SaveFile(f)
            data = {
                "status": 1,
                "message": u"cg",
                "data": []
            }
    except Exception as e:
        data = {
            "status": 0,
            "message": str(e),
            "data": []
        }
    # 对1.csv文件进行读取，并导入数据库
    # list = FileUtil.ReadCSV(fileName)
    # if len(list):
    #     for i in list:
    #         MySQLDB.CommitMySql("insert into t_sys_parts_sub1 (name) values ('%s');"%i["name"])

    jsonstr = json.dumps(data)
    return HttpResponse(jsonstr, content_type="application/json")


def LOGOUT(request):
    response = HttpResponseRedirect('/')
    response.delete_cookie('userid')
    response.delete_cookie('loginmd5')
    return response